import React from "react";
import TodoItem from "./TodoItem";
import "../../Styles/page.css";
import dayjs from "dayjs";

interface IProp {
  data: TodoListData | undefined;
  onDataChange: (data: TodoListData) => void;
}

export default function TodoList(props: IProp) {
  const { data, onDataChange: dataChangeHandler } = props;

  const finishHandler = (index: number) => {
    if (data !== undefined) {
      const copy = data.slice();
      copy[index].finished = !copy[index].finished;
      copy[index].mtime = dayjs().valueOf();
      dataChangeHandler(copy);
    }
  };

  const deleteHandler = (index: number) => {
    if (data !== undefined) {
      const copy = data.slice();
      copy.splice(index, 1);
      dataChangeHandler(copy);
    }
  };

  return (
    <div className="app-display">
      {data === undefined ? (
        <></>
      ) : (
        data.map((value, index) => (
          <TodoItem
            key={index}
            data={value}
            onFinish={() => {
              finishHandler(index);
            }}
            onDelete={() => {
              deleteHandler(index);
            }}
          />
        ))
      )}
    </div>
  );
}
